package dcp.bss.modules.sys.controller;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import dcp.bss.modules.sys.entity.SysUserEntity;
import dcp.bss.modules.sys.service.SysCaptchaService;
import dcp.bss.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import dcp.bss.common.util.Base64Util;
import dcp.bss.common.util.R;

import dcp.bss.modules.sys.form.SysLoginForm;
import dcp.bss.modules.sys.service.SysLogService;
import dcp.bss.modules.sys.service.SysUserService;

import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 登录相关
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
public class SysLoginController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private SysCaptchaService sysCaptchaService;

    /**
     * 验证码
     */
    @GetMapping("captcha")
    public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }



    @PostMapping("/sys/login")
    public R sysLogin(@RequestBody SysLoginForm loginForm, HttpServletRequest request) throws Exception {
        //验证码
//        boolean captcha = sysCaptchaService.validate(loginForm.getUuid(), loginForm.getCaptcha());
//        if(!captcha){
//            return R.error("验证码不正确");
//        }
        //访问一次，计数一次
        String newUsm = Base64Util.decode(loginForm.getUsername());
        newUsm = Base64Util.decode(newUsm);
        newUsm = Base64Util.decode(newUsm);
        String newPwd = Base64Util.decode(loginForm.getPassword());
        newPwd = Base64Util.decode(newPwd);
        newPwd = Base64Util.decode(newPwd);

        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(newUsm);
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(newPwd, user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }
        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }
        R result = sysUserTokenService.createToken(user.getUserId());
        result.put("username", user.getUsername());
        result.put("name", user.getIpName());
        return result;
    }


    @PostMapping("/sys/applogin")
    public R applogin(@RequestBody SysLoginForm loginForm, HttpServletRequest request) throws Exception {
        //用户信息
        SysUserEntity user = sysUserService.queryByUserName(loginForm.getUsername());
        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(loginForm.getPassword(), user.getSalt()).toHex())) {
            return R.error("账号或密码不正确");
        }
        //账号锁定
        if (user.getStatus() == 0) {
            return R.error("账号已被锁定,请联系管理员");
        }
        R result = sysUserTokenService.createToken(user.getUserId());
        result.put("username", user.getUsername());
        result.put("name", user.getIpName());
        return result;
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R logout(HttpServletRequest request) {
        sysLogService.addLogoutLog(request);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return R.ok("登出成功");
    }


}
